package com.zhihao.takeaway.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhihao.takeaway.common.utils.EasyUITable;
import com.zhihao.takeaway.common.utils.PageHelperUtil;
import com.zhihao.takeaway.entity.Marketer;
import com.zhihao.takeaway.mapper.MarketerMapper;
import com.zhihao.takeaway.service.CacheService;
import com.zhihao.takeaway.service.MarketerService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class MarketerServiceImpl extends ServiceImpl<MarketerMapper, Marketer>
    implements MarketerService {

    @Autowired
    private MarketerMapper marketerMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private Redisson redisson;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public EasyUITable getPageData(Integer nownum, Integer wantnum, String input) throws Exception {
//        IPage page = new Page(nownum,wantnum);
        Integer total = 0;
       if(input == null || input.equals("")){
           String lockKey = "marketer";
           RLock redissonLock = redisson.getLock(lockKey);
           try {
               redissonLock.lock(10, TimeUnit.SECONDS);
//               EasyUITable easyUITable = pageHelperUtil.getList(nownum, wantnum);
               List<Marketer> list = new ArrayList<>();
               List<Marketer> list1 = new ArrayList<>();
               String s = "marketer:0";
               if (!cacheService.hasKey(s)) {
                   list = getData();
                   for (int i = 0; i < list.size(); i++) {
                       cacheService.add("marketer:" + i, list.get(i),2000,TimeUnit.SECONDS);
                       if (i < wantnum) {
                           list1.add(list.get(i));
                       }
                   }
                   return new EasyUITable(list.size(), list1);
               } else {
                   for (int i = 0; i < wantnum; i++) {
                       Marketer marketer = cacheService.getObject("marketer:" + (nownum + i), Marketer.class);
                       if (marketer != null) {
                           list.add(marketer);
                       } else {
                           break;
                       }
                   }
                   return new EasyUITable(list);
               }
           } finally {
               redissonLock.unlock();
           }
       }else {
           //        条件搜索
           SearchRequest searchRequest = new SearchRequest("marketer_index");
           SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

//        分页
           searchSourceBuilder.from(nownum);
           searchSourceBuilder.size(wantnum);

//        模糊匹配
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
           MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("storeName", input);
           searchSourceBuilder.query(matchQueryBuilder);
           searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

//        高亮
           HighlightBuilder highlightBuilder = new HighlightBuilder();
           highlightBuilder.field("storeName");
           highlightBuilder.preTags("<span style='color:red;font-weight:600'>");
           highlightBuilder.postTags("</span>");
           searchSourceBuilder.highlighter(highlightBuilder);

//        执行搜索
           searchRequest.source(searchSourceBuilder);
           SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        解析结果

           ArrayList<Map<String,Object>> list = new ArrayList<>();
           for (SearchHit documentFields : search.getHits().getHits()) {
//            解析高亮字段
               Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
//            把所有的标题获取出来（高亮字段的标题）
               HighlightField title = highlightFields.get("storeName");
               Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();  // 原来的未高亮的字段
//            解析高亮字段
//            把高亮字段替换为原来没有高亮的字段
//            这一步是取出高亮字段
               if (title != null) {
                   Text[] fragments = title.fragments();
//                新的标题
                   String n_title = "";
                   for (Text text : fragments) {
                       n_title += text;
                   }
                   sourceAsMap.put("storeName", n_title); // 高亮字段替换掉原来的内容即可

               }
               list.add(sourceAsMap);
//            非高亮一步保存即可
               //            list.add(documentFields.getSourceAsMap());
           }
           System.out.println(list);
           return new EasyUITable(list.size(),list);
       }
    }

    @Override
    public EasyUITable getMoreData(Integer currentPage, Integer wantnum, String input) {
        IPage page = new Page(currentPage,wantnum);
        QueryWrapper<Marketer> queryWrapper = new QueryWrapper<>();
        if(input.equals("")){
            queryWrapper.lambda().like(Marketer::getStoreName,"");
        }else{
            queryWrapper.lambda().like(Marketer::getStoreName,input);
        }
        queryWrapper.select("id","name","id_number","sex","age","update_time","create_time","province_name","city_name","district_name","detail","label","phone","image","store_name");
        marketerMapper.selectPage(page,queryWrapper);
        Integer total = (int)page.getTotal();
        List<Marketer> list = page.getRecords();
        return new EasyUITable(total,list);
    }

    @Override
    public List<Marketer> getData() {
        QueryWrapper<Marketer>queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","name","image","account","store_name");
        List<Marketer>list = marketerMapper.selectList(queryWrapper);
        return list;
    }
}
